<template>
    <div>
        <el-dialog v-model="props.publicDialogEdit" @close="handlePublicEditClose" :fullscreen="true">
            <el-button type="primary" style=" margin: 0 0 20px 115px;" @click="addLanguage">
                添加语言
            </el-button>
            <el-row>
                <el-col :span="1">
                    <el-anchor v-model="containerRef" direction="vertical" type="default" :offset="30"
                        @change="handleClick">
                        <el-anchor-link href="#part1">
                            <el-text class="mb8" :type="containerRef == '#part1' ? 'primary' : ''">基本信息</el-text>
                        </el-anchor-link>
                        <el-anchor-link href="#part2">
                            <el-text class="mb8" :type="containerRef == '#part2' ? 'primary' : ''">SKU信息</el-text>
                        </el-anchor-link>
                        <el-anchor-link href="#part3">
                            <el-text class="mb8" :type="containerRef == '#part3' ? 'primary' : ''">商品SEO</el-text>
                        </el-anchor-link>
                        <el-anchor-link href="#part4">
                            <el-text class="mb8" :type="containerRef == '#part4' ? 'primary' : ''">商品图片</el-text>
                        </el-anchor-link>
                        <el-anchor-link href="#part5">
                            <el-text class="mb8" :type="containerRef == '#part5' ? 'primary' : ''">货源信息</el-text>
                        </el-anchor-link>
                    </el-anchor>
                </el-col>

                <el-col :span="23">
                    <el-tabs v-model="editableTabsValue" type="card" style="margin: 0 45px;" @tab-change="tabChange">
                        <el-tab-pane v-for="(item, index) in languageList" :key="item.languageId"
                            :name="item.languageId">
                            <template #label>
                                {{ item.languageName }}
                                <el-icon style="margin:0 10px;" v-if="item.languageId != editableTabsValue"
                                    @click.stop="removeTab(item, index)">
                                    <CircleCloseFilled />
                                </el-icon>
                            </template>
                        </el-tab-pane>
                    </el-tabs>
                    <div class="container_box">
                        <div v-for="(item, index) in languageList" :key="index">
                            <el-form :model="item" label-width="auto" :rules="publicRules" ref="publicFormRef"
                                v-if="index == choseIndex">
                                <div id="part1">
                                    <el-descriptions title="基本信息" />
                                    <el-form-item label="商品名称" prop="name" required>
                                        <el-input v-model.trim="item.name" placeholder="请输入">
                                            <template #append>
                                                <el-button
                                                    @click="translationTier('tier', index, item.languageId, item.name, 'name')"
                                                    :disabled="!item.name">翻译</el-button>
                                            </template> </el-input>
                                    </el-form-item>
                                    <el-form-item label="商品品牌" prop="brandId" required>
                                        <el-select v-model="item.brandId" placeholder="请选择">
                                            <el-option v-for="dict in product_brand" :key="dict.id"
                                                :label="dict.commonName" :value="dict.id" :disabled="!dict.status" />
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="商品分类" prop="publicRawCategoryIds">
                                        <el-select v-model="item.publicRawCategoryIds" placeholder="请选择" multiple
                                            collapse-tags collapse-tags-tooltip>
                                            <el-option v-for="dict in product_sort" :key="dict.id" :label="dict.name"
                                                :value="dict.id" />
                                        </el-select>
                                    </el-form-item>

                                    <el-form-item label="商品描述" prop="description">
                                        <Editor v-model="item.description" :height="200" :needImage="[]"
                                            :showHeight="true"></Editor>
                                    </el-form-item>
                                    <el-form-item label="商品属性" prop="attributes">
                                        <el-button class="mb8" type="primary"
                                            :disabled="!handleAttributes(1, item.productAttributeList?.length, item.productAttributeList)"
                                            @click="translationTier('attributes', index, item.languageId, item.productAttributeList)">翻译</el-button>
                                        <el-space spacer=" "
                                            v-for="(dict, attributesIndex) in item.productAttributeList"
                                            :key="attributesIndex" class="mb8">
                                            <el-input placeholder="属性名称" v-model="dict.name" style="width: 45vw;" />
                                            <el-input placeholder="属性值" v-model="dict.attributeContent"
                                                style="width: calc(55vw - 345px);">
                                            </el-input>
                                            <el-button type="danger" :icon="Delete"
                                                @click="removeStats(attributesIndex, dict)" />
                                        </el-space>
                                        <el-button class="addBtn" @click="addStats" type="primary"
                                            plain>添加属性</el-button>
                                    </el-form-item>
                                </div>
                                <div id="part2">
                                    <el-space spacer=" ">
                                        <el-descriptions title="SKU信息" />
                                        <el-button type="primary" style="margin-bottom: 15px;"
                                            :disabled="handleSku(item.newProductOptionVOList)"
                                            @click="translationTier('sku', index, item.languageId, item.newProductOptionVOList)">翻译</el-button>
                                    </el-space>
                                    <el-form-item v-for="(dict, VolIndex) in item.newProductOptionVOList"
                                        :key="VolIndex" :label="`规格-${VolIndex + 1}`">
                                        <el-space spacer=" " wrap>
                                            <el-space spacer=" ">
                                                <el-input placeholder="规格名" style="width: calc(100vw - 340px);"
                                                    class="mb8" v-model="dict.optionName">
                                                </el-input>
                                                <el-button type="danger" :icon="Delete"
                                                    @click="removeSkuBigList(index, VolIndex)"
                                                    v-if="showSkuBigList(item.newProductOptionVOList)" />
                                            </el-space>

                                            <el-space spacer=" "
                                                v-for="(option, optionIndex) in dict.publicUpdateProductOptionValueRequestList"
                                                :key="optionIndex">
                                                <el-input placeholder="规格值"
                                                    style="width: calc(100vw - 380px);margin-left: 40px;"
                                                    v-model="option.name">
                                                </el-input>
                                                <el-button type="danger" :icon="Delete"
                                                    @click="removeSkuList(index, VolIndex, optionIndex)"
                                                    v-if="showSkuList(item.newProductOptionVOList, dict.publicUpdateProductOptionValueRequestList)" />
                                            </el-space>
                                        </el-space>
                                        <el-button class="addBtn" type="primary" plain
                                            @click="addSkuList(index, VolIndex)">添加选项</el-button>
                                    </el-form-item>
                                    <el-form-item :label="`  `">
                                        <el-space spacer=" ">
                                            <el-tooltip effect="dark" content="保存 SKU 名称和值后，SKU 列表将自动刷新,请先保存再修改SKU列表数据。"
                                                placement="top-start">
                                                <el-button type="primary" @click="saveSku(item)">保存规格
                                                    <el-icon>
                                                        <QuestionFilled />
                                                    </el-icon>
                                                </el-button>
                                            </el-tooltip>
                                            <el-tooltip effect="dark" content="规格不能超过3个" placement="top-start"
                                                v-if="item.newProductOptionVOList?.length < 3">
                                                <el-button type="primary"
                                                    @click="addSkuBIgList(index, item.languageId)">新增规格
                                                    <el-icon>
                                                        <QuestionFilled />
                                                    </el-icon>
                                                </el-button>
                                            </el-tooltip>
                                        </el-space>
                                    </el-form-item>
                                    <el-form-item :label="`  `">
                                        <el-table :data="product_price_list" :row-style="rowStyle" border
                                            style="width: 100vw;">
                                            <el-table-column label="商品规格">
                                                <template #default="scope">
                                                    <el-text v-if="!scope.row.optionValueNames">默认规格</el-text>
                                                    <el-space spacer=" " direction="vertical" v-if="scope.$index">
                                                        <el-text
                                                            v-for="item in deepCopiedList[index]?.publicProductOptionVOList"
                                                            :key="item">{{ item.optionName }}：</el-text>
                                                    </el-space>
                                                    <el-space spacer=" " direction="vertical">
                                                        <el-text v-for="item in scope.row.optionValueNames"
                                                            :key="item">{{ item }}</el-text>
                                                    </el-space>


                                                </template>
                                            </el-table-column>
                                            <el-table-column prop="address" width="350">
                                                <template #header>
                                                    <el-space spacer=" " wrap>
                                                        {{ `价格(${product_price_list[0]?.currencyName})` }}
                                                        <el-button type="primary" link
                                                            @click="publicBatch(1)">批量设置</el-button>
                                                    </el-space>
                                                </template>
                                                <template #default="scope">
                                                    <el-space spacer=" " wrap>
                                                        <el-space spacer=" ">
                                                            <el-text>入库价</el-text>
                                                            <el-input-number v-model="scope.row.collectionPrice"
                                                                controls-position="right" placeholder="请输入"
                                                                style="width: 200px;" :min="0" :precision="2"
                                                                disabled />
                                                        </el-space>
                                                        <el-space spacer=" ">
                                                            <el-text>划线价</el-text>
                                                            <el-input-number v-model="scope.row.crossedPrice"
                                                                controls-position="right" placeholder="请输入"
                                                                style="width: 200px;" :min="0" :precision="2" />
                                                        </el-space>
                                                        <el-space spacer=" ">
                                                            <el-text>销售价</el-text>
                                                            <el-input-number v-model="scope.row.sellingPrice"
                                                                controls-position="right" placeholder="请输入"
                                                                style="width: 200px;" :min="0" :precision="2" />
                                                        </el-space>
                                                    </el-space>
                                                </template>
                                            </el-table-column>

                                            <el-table-column align="center">
                                                <template #header>
                                                    <el-space spacer=" ">
                                                        <el-text>包裹重量</el-text>
                                                        <el-button type="primary" link
                                                            @click="publicBatch(2)">批量设置</el-button>
                                                    </el-space>
                                                </template>
                                                <template #default="scope">
                                                    <el-input type="number" placeholder="请输入" v-model="scope.row.weight"
                                                        :min="0">
                                                        <template #append>
                                                            <el-select v-model="scope.row.weightUnit" placeholder="请选择"
                                                                style="width: 90px;">
                                                                <el-option v-for="item in sys_weight_unit"
                                                                    :key="item.value" :label="item.label"
                                                                    :value="item.value" />
                                                            </el-select>
                                                        </template>
                                                    </el-input>
                                                </template>
                                            </el-table-column>
                                            <el-table-column width="400">
                                                <template #header>
                                                    <el-space spacer=" ">
                                                        <el-text>包裹尺寸（cm）</el-text>
                                                        <el-button type="primary" link
                                                            @click="publicBatch(0)">批量设置</el-button>
                                                    </el-space>
                                                </template>
                                                <template #default="scope">
                                                    <el-space spacer=" " wrap>
                                                        <el-space spacer=" ">
                                                            <el-text>长</el-text>
                                                            <el-input-number v-model="scope.row.length"
                                                                controls-position="right" placeholder="请输入"
                                                                style="width: 300px;" :min="0" :precision="2" />
                                                        </el-space>
                                                        <el-space spacer=" ">
                                                            <el-text>宽</el-text>
                                                            <el-input-number v-model="scope.row.width"
                                                                controls-position="right" :min="0" :precision="2"
                                                                placeholder="请输入" style="width: 300px;" />
                                                        </el-space>
                                                        <el-space spacer=" ">
                                                            <el-text>高</el-text>
                                                            <el-input-number v-model="scope.row.height"
                                                                controls-position="right" :min="0" :precision="2"
                                                                placeholder="请输入" style="width: 300px;" />
                                                        </el-space>
                                                    </el-space>
                                                </template>
                                            </el-table-column>
                                        </el-table>
                                    </el-form-item>
                                </div>
                                <div id="part3" style="border-bottom: 1px solid #ccc;" class="mb8">
                                    <el-space spacer=" ">
                                        <el-descriptions title="商品SEO" /><el-button type="primary"
                                            style="margin-bottom: 15px;"
                                            :disabled="productSeoTier(item.seoTitle, item.seoKeywords, item.tags, item.seoDescription)"
                                            @click="translationTier('seo', index, item.languageId, item)">翻译</el-button>
                                    </el-space>
                                    <el-form-item label="标题" prop="seoTitle">
                                        <el-input v-model.trim="item.seoTitle" placeholder="请输入" maxlength="100"
                                            show-word-limit type="text">
                                        </el-input>
                                    </el-form-item>
                                    <el-form-item label="关键字" prop="seoKeywords">
                                        <el-input v-model.trim="item.seoKeywords" placeholder="请输入" maxlength="100"
                                            show-word-limit type="text">
                                        </el-input>
                                    </el-form-item>
                                    <el-form-item label="商品标签" prop="tags">
                                        <el-input v-model.trim="item.tags" placeholder="请输入">
                                        </el-input>
                                    </el-form-item>
                                    <el-form-item label="描述" prop="seoDescription">
                                        <el-input v-model.trim="item.seoDescription" placeholder="请输入" maxlength="300"
                                            show-word-limit type="text">
                                        </el-input>
                                    </el-form-item>
                                </div>
                            </el-form>
                        </div>
                        <div ref="containerRef" style="margin: 20px 0;">
                            <div id="part4">
                                <el-descriptions title="图片信息" />
                                <ProductImage :Item="props.publicFrom" :clearIndex="clearIndex" :productImageType="1">
                                </ProductImage>
                            </div>
                            <div id="part5">
                                <el-space spacer=" ">
                                    <el-descriptions title="货源信息" />
                                    <el-button type="primary" style="margin-bottom: 15px;"
                                        @click="addCargo">新增</el-button>
                                </el-space>

                                <div v-for="(cargo, index) in product_cargo" :key="cargo">
                                    <el-space spacer=" ">
                                        <el-input v-model="cargo.remark" placeholder="备注"
                                            style="width: 500px;margin: 10px 0;" clearable />
                                        <el-input v-model="cargo.sourceUrl" placeholder="货源URL链接"
                                            style="width: calc(100vw - 920px);" clearable />
                                        <el-button type="primary" target="_blank" tag="a" :href="cargo.sourceUrl"
                                            :disabled="sourceUrlDisabled(cargo.sourceUrl)">跳转</el-button>
                                        <el-button type="primary" v-copyText="cargo.sourceUrl"
                                            v-copyText:callback="copyTextSuccess"
                                            :disabled="!cargo.sourceUrl">复制</el-button>
                                        <el-button type="danger" @click="removeCargo(index, cargo)">删除</el-button>
                                    </el-space>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div style="margin: 20px 0 10px 45vw;">
                        <el-button type="primary" @click="submitFrom">保存</el-button>
                        <el-button type="primary">一键翻译</el-button>
                    </div>
                </el-col>
            </el-row>
        </el-dialog>
        <AddProductLanguage :publicLanguageList="languageList" :dialogLanguage="dialogLanguage"
            @handleLanguageClose="handleLanguageClose" @handleLanguageSure="handleLanguageSure"></AddProductLanguage>
        <PublicBatch :dialogPrice="dialogPrice" @handlePriceClose="handlePriceClose" :choseType="choseType"
            @handlePriceSure="handlePriceSure"></PublicBatch>
    </div>
</template>
<script setup>
import { ref, defineProps, defineEmits, watch, reactive, onMounted, registerRuntimeCompiler } from "vue";
import AddProductLanguage from '../product/components/addProductLanguage.vue'
import ProductImage from '../product/components/productImage.vue'
import PublicBatch from '../product/components/publicBatch.vue'

import {
    Delete,
} from '@element-plus/icons-vue'
const { proxy } = getCurrentInstance();
const emits = defineEmits(["handleEditClose", "handlePriceSure"]);
const { sys_weight_unit } = proxy.useDict("sys_weight_unit");

const props = defineProps({
    publicFrom: {
        type: Object,
        default: {},
    },

    publicDialogEdit: {// 默认隐藏
        type: Boolean,
        default: false,
    },
});

// console.log(props.publicItem);
const containerRef = ref('#part1')// 默认选择锚点
const editableTabsValue = ref(0)// 默认选择第一个语言
const choseIndex = ref(0)//选择语言的下标

const product_sort = ref([])//个人商品分类
const product_brand = ref([])//商品品牌
const product_cargo = ref([])//货源列表
const product_price_list = ref([])//批量价格列表

const deepCopiedList = ref([])//深拷贝数据
const synchronizationAttributes = ref([])//同步属性数据（添加语言时，会用到）
const synchronizationSku = ref({})//同步SKU数据（添加语言时，会用到）

const languageList = ref([])
const dialogLanguage = ref(false)
const dialogPrice = ref(false)//默认不显示批量改价弹出框
const choseType = ref(0)//类型0是批量修改包裹尺寸，1是批量修改价格，2是批量修改包裹重量

const clearIndex = ref(0)//打开弹出框的时候清除照片选择的数据

const parameters = reactive({
    pageNum: 1,
    pageSize: 999,
})

watch(
    () => props.publicDialogEdit,
    () => {
        editableTabsValue.value=0
        if (props.publicDialogEdit) {
            getEchoDetails()//获取回显数据
            product_cargo_list()//获取货源列表
            clearIndex.value += 1
        } else {
            clearIndex.value = 0
        }

    }
);
const submitFrom = () => {
    if (!newValidateList()) return
    if (!bulkPrice()) return proxy.$modal.msgError(`请完整填写商品规格价格`)
    if (checkCargo()) return
    publicPriceList()
}
const publicPriceList = () => {
    product.general.publicproductBatchupdateprice(
        { data: product_price_list.value }
    ).then(res => {
        if (res.code === 200) {
            saveDateLanguage()
            getBatchPrice()//获取批量价格列表数据
            proxy.$modal.msgSuccess(res.message)
        }
    })
}
const saveDateLanguage = () => {
    product.general.publicproductSavetranslatedata({ data: languageList.value[choseIndex.value] }
    ).then(res => {
        if (res.code === 200) {
            saveCargo()
            RefreshDate()
        }
    })
}
const saveCargo = () => {
    // console.log(product_cargo.value);
    // return
    product.general.publicproductresourceurlEdit({
        data: product_cargo.value.length ? product_cargo.value : [{ publicProductId: props.publicFrom.id }]
    }).then(res => {
        if (res.code === 200) {
            product_cargo_list()//获取货源列表
        }
    })
}


// 获取回显数据
const getEchoDetails = () => {
    product.general.publicproductGettranslatedata({ data: { id: props.publicFrom.id } }
    ).then(res => {
        if (res.code === 200) {
            deepCopiedList.value = JSON.parse(JSON.stringify(res.data));
            console.log(deepCopiedList.value);
            languageList.value = []
            containerRef.value = '#part1'
            editableTabsValue.value = res.data[0].languageId
            choseIndex.value = 0//默认总是选择第一个
            res.data = res.data.map(code => {
                return {
                    ...code,
                    brandId: code.brandId ? code.brandId : null,
                    publicProductId: props.publicFrom.id,
                    publicRawCategoryIds: code.productRawCategoryLineVOList,
                    productAttributeList: product_attributes(code.publicProductAttributeLineVOList),//商品属性处理“name”
                    newProductOptionVOList: newProductOptionVOList(code.publicProductOptionVOList, code.languageId)//商品规格
                }
            })
            languageList.value = res.data
            getBatchPrice()//获取批量价格列表数据
        }
    })
}
const addStats = () => {//添加属性
    transformArray(languageList.value.length - 1).forEach(addIndex => {
        languageList.value[addIndex].productAttributeList.push({
            name: '',//属性名称
            attributeContent: '',//属性值
        })
        synchronizationAttributes.value = JSON.parse(JSON.stringify(languageList.value[addIndex].productAttributeList));

    })
}
const handleLanguageSure = (from) => {
    languageList.value.push({
        publicProductId: props.publicFrom.id,//产品ID
        languageId: from.languageId,//语言id
        languageName: from.languageName,//语言名称
        name: deepCopiedList.value[0]?.name,//商品名称
        brandId: deepCopiedList.value[0]?.brandId,//商品品牌
        publicRawCategoryIds: deepCopiedList.value[0]?.publicRawCategoryIds,//商品分类
        description: deepCopiedList.value[0]?.description,//商品描述
        productAttributeList: synchronizationAttributes.value.length ? synchronizationAttributes.value : product_attributes(languageList.value[0].publicProductAttributeLineVOList),//商品属性

        newProductOptionVOList: newPushSku(synchronizationSku.value.length, from),//商品规格
        seoDescription: languageList.value[0].seoDescription, //SEO描述
        seoKeywords: languageList.value[0].seoKeywords, //SEO关键字
        seoTitle: languageList.value[0].seoTitle,//SEO标题
        tags: languageList.value[0].tags //SEO标签
    })
    dialogLanguage.value = false
}
const addLanguage = () => {//添加语言
    dialogLanguage.value = true
}
const publicRules = ref({//校验规则
    name: [{ required: true, message: "请输入", trigger: "blur" }],
    brandId: [{ required: true, message: "请请选择", trigger: "blur" }],

})
const rowStyle = ({ row, rowIndex }) => {
    if (!rowIndex) {
        return { background: '	#b2db8f82' }; // 设置背景色和文本颜色
    } else {
        return {};
    }
};
onMounted(() => {
    getList()
})
const getList = () => {
    let from = { ...parameters, param: {} }
    product.brand.list({ data: from }).then((response) => {  // 商品品牌
        product_brand.value = response.data;
    });
    product.rawcategory.rawcategoryList({
        data: from
    }).then((res) => {//个人商品分类
        product_sort.value = res.data;
    })
}
const product_cargo_list = () => {
    product.general.publicproductresourceurlList({
        data: {
            ...parameters,
            param: { productId: props.publicFrom.id, },
        },
    }).then(res => {//货源列表
        if (res.data?.length) {
            res.data = res.data.map(code => {
                return { ...code, publicProductId: props.publicFrom.id }
            })
        }
        // publicProductId
        product_cargo.value = res.data
    })
}
const getBatchPrice = () => {//批量价格列表
    product.general.publicproductGetpricelist({
        data: {
            ...parameters,
            param: { publicProductIds: [props.publicFrom.id] }
        }
    }).then(res => {
        if (res.data?.length) {
            res.data = res.data.map(code => {
                return {
                    ...code,
                    publicProductId: code.productId,
                    publicProductOptionSkuId: code.productOptionSkuId,
                    weightUnit: code.weightUnit ? code.weightUnit : 'G'
                }
            })
        }
        product_price_list.value = res.data
    })
}
const handleCargo = () => {//货源编辑接口
    let newList = product_cargo.value.map(({ id, ...rest }) => rest);
    product.general.productresourceurlEdit({
        data: newList
    }).then(res => {
        if (res.code === 200) {
            product_cargo_list.value()
        }
    })
}
const tabChange = (e) => {//选择语言
    choseIndex.value = languageList.value.findIndex(code => code.languageId === e)
    editableTabsValue.value = deepCopiedList.value[0].languageId
    // console.log(editableTabsValue, e, 'activeName 改变时触发', choseIndex.value);
}
const removeTab = (item, index) => {//移除语言ID
    let deleteIndex = deepCopiedList.value.find(e => e.languageId == item.languageId)
    let newTips = deleteIndex ? '删除将清空本语言下的所有翻译数据，请确认是否需要删除！' : '是否确认删除此语言项？'
    proxy.$modal.confirm(newTips).then(() => {
        if (deleteIndex) {

            product.general.publicproductDeletetranslatedata({
                data: {
                    publicProductId: props.publicFrom.id,
                    languageId: item.languageId
                }
            }).then(res => {
                if (res.code === 200) {
                    RefreshDate()
                    languageList.value.splice(index, 1)
                    choseIndex.value = languageList.value.length - 1
                    proxy.$modal.msgSuccess(res.message)
                }
            })
        } else {
            languageList.value.splice(index, 1)
            // editableTabsValue.value = languageList.value[languageList.value.length - 1].languageId
            choseIndex.value = languageList.value.length - 1
        }
    })

}
const product_attributes = (list) => {//商品属性处理“name”
    if (!list) return []
    return list?.map(code => {
        return {
            ...code,
            name: code.productAttributeName,//属性名称
        }
    })
}
const newProductOptionVOList = (list, languageId) => {
    let newList = []
    if (!list) newList
    list?.forEach(element => {
        newList.push({
            publicOptionId: element.optionId,
            languageId: languageId,
            optionName: element.optionName,
            publicProductId: props.publicFrom.id,
            publicUpdateProductOptionValueRequestList: insideList(element.productOptionValueVOList)
        })
    });
    return newList
}
const insideList = (list) => {
    return list = list.map(code => {
        return {
            publicOptionId: code.optionId,
            publicOptionValueId: code.optionValueId,
            name: code.name
        }
    })
}

const removeStats = (attributesIndex, row) => {//删除属性
    transformArray(languageList.value.length - 1).forEach(addIndex => {
        languageList.value[addIndex].productAttributeList.splice(attributesIndex, 1);
        synchronizationAttributes.value = JSON.parse(JSON.stringify(languageList.value[addIndex].productAttributeList));
    })
}

const addSkuList = (index, VolIndex) => {//新增SKU选项值
    transformArray(languageList.value.length - 1).forEach(addIndex => {
        languageList.value[addIndex].newProductOptionVOList[VolIndex].publicUpdateProductOptionValueRequestList.push({ name: '' })
        synchronizationSku.value = JSON.parse(JSON.stringify(languageList.value[addIndex].newProductOptionVOList));
    })
    // languageList.value[index].newProductOptionVOList[VolIndex].publicUpdateProductOptionValueRequestList.push({ name: '' })
}
const removeSkuList = (index, VolIndex, optionIndex) => {//删除SKU选项值
    transformArray(languageList.value.length - 1).forEach(addIndex => {
        languageList.value[addIndex].newProductOptionVOList[VolIndex].publicUpdateProductOptionValueRequestList.splice(optionIndex, 1)
        synchronizationSku.value = JSON.parse(JSON.stringify(languageList.value[addIndex].newProductOptionVOList));
    })
}
const removeSkuBigList = (index, VolIndex) => {//删除SKU大的规格
    transformArray(languageList.value.length - 1).forEach(addIndex => {
        languageList.value[addIndex].newProductOptionVOList.splice(VolIndex, 1)
        synchronizationSku.value = JSON.parse(JSON.stringify(languageList.value[addIndex].newProductOptionVOList));

    })
}
const addSkuBIgList = (index, languageId) => {//新增SKU选项值
    transformArray(languageList.value.length - 1).forEach(addIndex => {
        languageList.value[addIndex].newProductOptionVOList.push({
            languageId: languageList.value[addIndex].languageId,
            optionName: '',
            productId: props.publicFrom.id,
            publicUpdateProductOptionValueRequestList: []
        })
        let VolIndex = languageList.value[addIndex].newProductOptionVOList.length - 1
        languageList.value[addIndex].newProductOptionVOList[VolIndex].publicUpdateProductOptionValueRequestList.push({
            name: ''
        })
        synchronizationSku.value = JSON.parse(JSON.stringify(languageList.value[addIndex].newProductOptionVOList));
    })
}
const newPushSku = (index, from) => {//新增语言时，SKU数据重新push一下，防止数据同步
    let newList = [];
    if (index) {
        synchronizationSku.value.forEach(item => newList.push(item))
    } else {
        newProductOptionVOList(languageList.value[0].publicProductOptionVOList, from.languageId).forEach(item => newList.push(item))
    }
    return newList
}
const translationTier = (type, index, languageId, content, assignment) => {//翻译==tier
    let newContent = ''
    if (type === 'tier') {
        newContent = content
    } else if (type === 'seo') {
        newContent = `${content.seoTitle}||||${content.seoKeywords}||||${content.tags}||||${content.seoDescription}`
    } else if (type === 'attributes') {
        newContent = content.map(item => `${item.name}||||${item.attributeContent}`).join("|||||");
    } else {
        let optionNames = content.map(item => item.optionName).join("||||"); // 提取 optionName
        // 提取 productOptionValueVOList 中的 name
        let optionValues = content.flatMap(item => item.publicUpdateProductOptionValueRequestList.map(value => value.name)).join("||||");
        newContent = `${optionNames}|||||${optionValues}`;// 拼接最终字符串
    }
    product.general.productTranslate({
        data: {
            sourceLanguageId: deepCopiedList.value[0].languageId,//源语言ID
            targetLanguageId: languageId,//目标语言ID
            productId: props.publicFrom.id,//产品ID
            translateContent: newContent//翻译内容
        }
    }).then(res => {
        if (res.code === 200) {
            console.log(res.data.translateData);
            if (type === 'tier') {
                languageList.value[index][assignment] = res.data.translateData

            } else if (type === 'seo') {
                // console.log( res.data.translateData.split(','));
                languageList.value[index].seoTitle = res.data.translateData.split('||||')[0]
                languageList.value[index].seoKeywords = res.data.translateData.split('||||')[1]
                languageList.value[index].tags = res.data.translateData.split('||||')[2]
                languageList.value[index].seoDescription = res.data.translateData.split('||||')[3]
            } else if (type === 'attributes') {
                let list = res.data.translateData.split("|||||");
                // console.log(list);
                languageList.value[index].productAttributeList = list.map((item, index) => {
                    let parts = item.split('||||');
                    // console.log(parts);
                    return {
                        ...item,
                        name: parts[0],
                        attributeContent: parts[1], // 处理可能含有多个内容值的情况
                    }
                })
            } else {
                let list = res.data.translateData.split("|||||");
                console.log(list);
            }
        }
    })
}
const productSeoTier = (seoTitle, seoKeywords, tags, seoDescription) => {//当全部的商品SEo填写了，则返回false
    if (seoTitle || seoKeywords || tags || seoDescription) return false
    return true
}
const saveSku = (row) => {//保存规格
    if (handleSku(row.newProductOptionVOList)) return proxy.$modal.msgError(`完整填写规格`);
    product.general.publicproductoptionlineUpdate(
        { data: row.newProductOptionVOList }
    ).then(res => {
        if (res.code === 200) {
            product.general.publicproductGettranslatedata({ data: { id: props.publicFrom.id } }
            ).then(res => {
                if (res.code === 200) {
                    deepCopiedList.value = JSON.parse(JSON.stringify(res.data));
                    getBatchPrice()//批量改价列表数据
                }
            })
        }
    })
}
const publicBatch = (index) => {
    choseType.value = index
    dialogPrice.value = true
}
const handlePriceClose = () => {
    dialogPrice.value = false//不显示批量弹出框
}
const handlePriceSure = (from) => {
    if (choseType.value === 1) {//价格
        handlePrice(from)
    } else if (choseType.value === 2) {//重量
        handleWeight(from)
    } else {//尺寸
        dimensionStacked(from)

    }
    dialogPrice.value = false//不显示批量弹出框
}
const handlePrice = (from) => {
    let list = []
    if (from.resource === 1) {//crossedPrice：划线价
        if (from.resourcePrice == 1) {//改价
            list = product_price_list.value.map(code => {
                return {
                    ...code,
                    crossedPrice: from.several,
                }
            })
        } else if (from.resourcePrice == 2) {//加价
            list = product_price_list.value.map(code => {
                return {
                    ...code,
                    crossedPrice: code.crossedPrice + from.several,
                }
            })
        } else {
            list = product_price_list.value.map(code => {
                return {
                    ...code,
                    crossedPrice: code.crossedPrice - from.several,
                }
            })
        }

        product_price_list.value = list
    } else {//sellingPrice：销售价
        if (from.resourcePrice == 1) {//改价
            list = product_price_list.value.map(code => {
                return {
                    ...code,
                    sellingPrice: from.several,
                }
            })
        } else if (from.resourcePrice == 2) {//加价
            list = product_price_list.value.map(code => {
                return {
                    ...code,
                    sellingPrice: code.sellingPrice + from.several,
                }
            })
        } else {
            list = product_price_list.value.map(code => {
                return {
                    ...code,
                    sellingPrice: code.sellingPrice - from.several,
                }
            })
        }
        product_price_list.value = list
    }
}
const handleWeight = (from) => {
    let list = []
    if (from.resourcePrice === 1) {
        list = product_price_list.value.map(code => {
            console.log(from.unit, code.weight);
            return {
                ...code,
                weight: from.several,
                weightUnit: from.unit
            }
        })
        product_price_list.value = list
    } else if (from.resourcePrice === 2) {
        list = product_price_list.value.map(code => {
            return {
                ...code,
                weight: code.weight + from.several,
                weightUnit: from.unit
            }
        })
        product_price_list.value = list

    } else {
        list = product_price_list.value.map(code => {
            return {
                ...code,
                weight: code.weight - from.several,
                weightUnit: from.unit
            }
        })
        product_price_list.value = list
    }
}
const dimensionStacked = (from) => {
    let list = []
    list = product_price_list.value.map(code => {
        console.log(from.unit, code.weight);
        return {
            ...code,
            length: from.length,
            width: from.width,
            height: from.height
        }
    })
    product_price_list.value = list
}


const transformArray = (length) => {
    let indexArray = []
    indexArray = Array(length + 1).fill().map((_, index) => index);
    return indexArray
}
const newValidateList = () => {
    var publicLanguageFrom = {}
    publicLanguageFrom = languageList.value[choseIndex.value]
    if (!publicLanguageFrom.name || publicLanguageFrom.name.trim() === "") {
        proxy.$modal.msgError(` ${publicLanguageFrom.languageName} 语言的”商品名称“不能为空`);
        return false
    }
    // // 检查 productAttributeList 里的 name 和 attributeContent 不能为空
    if (!handleAttributes(0, publicLanguageFrom.productAttributeList.length, publicLanguageFrom.productAttributeList)) {
        proxy.$modal.msgError(`完整填写${publicLanguageFrom.languageName}语言的商品属性`);
        return false
    }

    // 检查 newProductOptionVOList 里的 optionName 和 publicUpdateProductOptionValueRequestList的name 不能为空
    if (handleSku(publicLanguageFrom.newProductOptionVOList)) {
        proxy.$modal.msgError(`完整填写${publicLanguageFrom.languageName}语言的规格`);
        return false
    } else {
        return true
    }
}
const handleAttributes = (newIndex, length, list) => {//商品属性
    if (newIndex) {
        if (!length) return false
        console.log();
        return !list.some(item => item.name == '' || item.productAttributeName == '')
    } else {
        if (length) {
            if (list.some(item => item.name == '' || item.productAttributeName == '')) {
                return false
            } else {
                return true
            }
        } else {
            return true
        }
    }
}


const handleSku = (rowList) => {//检查规格
    let handleList
    handleList = rowList.some(item => item.optionName == '' || item.publicUpdateProductOptionValueRequestList?.some(value => value.name === ''))
    return handleList
}
const bulkPrice = () => {//批量价格
    let hasNullValues = !product_price_list.value.some(item => item.crossedPrice === null ||
        item.sellingPrice === '' ||
        item.weight === '' ||
        item.weightUnit === '' ||
        item.length === '' ||
        item.width === '' ||
        item.height === '')
    return hasNullValues
}
const checkCargo = () => {
    if (!product_cargo.value.length) return false
    if (product_cargo.value.some(item => item.sourceUrl == '')) {
        proxy.$modal.msgError(`请完整填写货源URL`);
        return true
    }
    if (product_cargo.value.some(item => sourceUrlDisabled(item.sourceUrl))) {
        proxy.$modal.msgError(`请正确填写货源URL`);
        return true
    }
    return false
}
const copyTextSuccess = () => {/** 复制代码成功 */
    proxy.$modal.msgSuccess("复制成功");
}
const handleClick = (e) => {
    containerRef.value = e//选择的锚点
}
const handlePublicEditClose = () => {
    emits('handlePublicEditClose')
}
const handleLanguageClose = () => {
    dialogLanguage.value = false
}
const removeCargo = (index, row) => {//删除货源
    product_cargo.value.splice(index, 1);
}
const addCargo = () => {//新增货源
    product_cargo.value.push({
        remark: '',//备注
        sourceUrl: '',//货源地址
        publicProductId: props.publicFrom.id
    })
}
const showSkuBigList = (list) => {
    if (list.length <= 1) {
        return false
    } else {
        return true
    }
}
const sourceUrlDisabled = (sourceUrl) => {
    let pattern = /^(http|https):\/\/([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}(:\d+)?(\/.*)?$/
    pattern.test(sourceUrl)
    return !pattern.test(sourceUrl)
}
const showSkuList = (list, smallList) => {
    if (list.length <= 1 && smallList.length <= 2) {
        return false
    } else {
        return true
    }
}
const RefreshDate = () => {
    product.general.publicproductGettranslatedata({ data: { id: props.publicFrom.id } }
    ).then(res => {
        if (res.code === 200) {
            deepCopiedList.value = JSON.parse(JSON.stringify(res.data));
        }
    })
}
</script>
<style lang="scss" scoped>
.container_box {
    height: calc(100vh - 220px);
    overflow-y: auto;
    position: relative;
    width: calc(100vw - 140px);
    padding: 0 20px;
}

.addBtn {
    width: 100vw;
    margin: 20px 0;
    height: 45px;
}
</style>